import pygame
import random

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 加载背景图片
try:
    BACKGROUND_IMAGE = pygame.image.load("back.png")  # 图片路径
    BACKGROUND_IMAGE = pygame.transform.scale(BACKGROUND_IMAGE, (SCREEN_WIDTH, SCREEN_HEIGHT))
except Exception as e:
    print("加载背景图片失败:", e)
    BACKGROUND_IMAGE = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
    BACKGROUND_IMAGE.fill((255, 255, 255))  # 失败时使用白色背景

# 颜色定义
COLORS = [
    (255, 0, 0),  # 红
    (0, 255, 0),  # 绿
    (0, 0, 255),  # 蓝
    (255, 255, 0),  # 黄
    (128, 0, 128)  # 紫
]
BG_COLOR = (255, 255, 255)
SLOT_COLOR = (200, 200, 200)

# 主循环
clock = pygame.time.Clock()
running = True


# 卡片尺寸和间距
CARD_WIDTH = 60
CARD_HEIGHT = 80
SPACING = 10

# 游戏区域布局
GRID_ROWS = 3
GRID_COLS = 3
GRID_TOP = 100

# 初始化卡片堆（每个位置3-4层）
grid = []
for row in range(GRID_ROWS):
    grid_row = []
    for col in range(GRID_COLS):
        layers = random.randint(3, 4)
        # 确保卡片类型数量为3的倍数
        stack = [random.randint(0, len(COLORS) - 1) for _ in range(layers)]
        stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
        grid_row.append(stack)
    grid.append(grid_row)

# 游戏状态
slots = []
score = 0
game_over = False
game_won = False


def check_victory():
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


# 主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x, y = pygame.mouse.get_pos()
            # 计算点击位置
            grid_col = (x - SPACING) // (CARD_WIDTH + SPACING)
            grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
            # 检查点击范围
            if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                if len(grid[grid_row][grid_col]) > 0:
                    # 取出顶层卡片
                    card = grid[grid_row][grid_col].pop()
                    slots.append(card)
                    # 检查连续三个
                    if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                        del slots[-3:]
                        score += 1
                    # 检查失败条件
                    if len(slots) > 7:
                        game_over = True
                    # 检查胜利条件
                    if check_victory():
                        game_won = True
                        game_over = True

    # 绘制界面
    screen.fill(BG_COLOR)
    screen.blit(BACKGROUND_IMAGE, (0, 0))  # 替换原来的screen.fill()
    # 绘制卡片堆
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = SPACING + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            if len(grid[row][col]) > 0:
                pygame.draw.rect(screen,
                                 COLORS[grid[row][col][-1]],
                                 (x, y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制槽位
    slot_y = SCREEN_HEIGHT - CARD_HEIGHT - 20
    for i, card in enumerate(slots):
        pygame.draw.rect(screen,
                         COLORS[card],
                         (20 + i * (CARD_WIDTH + 5), slot_y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制状态信息
    font = pygame.font.Font(None, 36)
    text = font.render(f"Score: {score}", True, (0, 0, 0))
    screen.blit(text, (20, 20))

    if game_over:
        text = font.render("YOU WIN!" if game_won else "GAME OVER!",
                           True, (0, 255, 0) if game_won else (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()